import React from 'react'
import {
  Form,
  Select,
  Button,
  Radio,
  DatePicker,
  InputNumber,
  Checkbox,
  message,
  TimePicker,
  Modal,
  Input
} from 'antd'
import _ from 'lodash'
import {
  projectFindBypageApi,
  tuserFindBypageApi,
  maintaskFindApi,
  productFindBypageApi,
  maintaskUpdateApi
} from '../api/ajax'
import moment from 'moment'
import { checkTime } from './Task'
const FormItem = Form.Item
const Option = Select.Option
const RadioGroup = Radio.Group

class EditTask extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      projectSource: [],
      userSource: [],
      effStartDate: false,
      executionType: 0,
      monthType: null,
      executionMode: null,
      visible: false,
      productSource: [],
      selectedRowKeys: [],
      selectedProductData: []
    }
  }
  componentDidMount() {
    this.loadData()
  }
  loadData = () => {
    projectFindBypageApi().then(v => {
      const {
        list: { results }
      } = v
      this.setState({
        projectSource: results ? results : []
      })
    })
    tuserFindBypageApi().then(v => {
      const {
        list: { results }
      } = v
      this.setState({
        userSource: results ? results : []
      })
    })
    productFindBypageApi().then(v => {
      const {
        list: { results }
      } = v
      this.setState({ productSource: results ? results : [] })
    })
    maintaskFindApi({ id: this.props.match.params.id }).then(res => {
      let values = {}
      this.setState({
        effStartDate: res.effectiveTime === 2 ? true : false,
        executionType: res.executionType,
        monthType: res.monthType,
        executionMode: res.executionMode
      })
      values.effectiveTime = res.effectiveTime
      values.executionType = res.executionType
      values.executionMode = res.executionMode
      values.monthType = res.monthType
      values.monthDay = res.monthDay
      values.projectId = res.projectId
      values.taskCode = res.taskCode
      values.updateType = res.updateType
      values.sourceId = res.sourceId
      values.isSubFile = res.isSubFile
      values.timeList = res.timeList
      values.aimsIds = res.aimsIds.split(',')
      if (res.week) values.week = res.week.split(',')
      values.startDate = moment(res.startDate, 'YYYY-MM-DD hh:mm:ss')
      values.timeNum = res.timeNum
      values.timeType = res.timeType && res.timeType.toString()
      if (res.effStartDate && res.effEndDate) {
        values.effStartDate = [
          moment(res.effStartDate, 'YYYY-MM-DD hh:mm:ss'),
          moment(res.effEndDate, 'YYYY-MM-DD hh:mm:ss')
        ]
      }
      if (res.exStartDate)
        values.exStartDate = moment(res.exStartDate, 'YYYY-MM-DD hh:mm:ss')

      if (res.exEndDate)
        values.exEndDate = moment(res.exEndDate, 'YYYY-MM-DD hh:mm:ss')
      this.props.form.setFieldsValue(values)
    })
  }
  save = () => {
    const { validateFields } = this.props.form
    validateFields((errors, values) => {
      if (errors) return
      let id = this.props.match.params.id
      let history = this.props.history
      if (
        values.executionMode == 2 &&
        _.isString(values.timeList) &&
        !checkTime(values.timeList)
      ) {
        message.error('执行多次(无规律)时间格式错误')
        return
      }
      Modal.confirm({
        title: '是否使用最新开始文件时间',
        okText: '是',
        cancelText: '否',
        onOk() {
          let obj = {}
          obj.id = id
          obj.effectiveTime = values.effectiveTime
          obj.executionType = values.executionType
          obj.executionMode =
            values.executionMode == null ? 3 : values.executionMode
          obj.monthType = values.monthType
          obj.monthDay = values.monthDay
          obj.projectId = values.projectId
          obj.startDate = values.startDate
          obj.taskCode = values.taskCode
          obj.updateType = values.updateType
          obj.aimsIds = values.aimsIds
          obj.sourceId = values.sourceId
          obj.isSubFile = values.isSubFile
          obj.timeList = values.timeList
          obj.isChangeDate = 0
          if (values.exStartDate) obj.exStartDate = values.exStartDate

          if (values.exEndDate) obj.exEndDate = values.exEndDate

          if (values.effectiveTime === 2) {
            obj.effStartDate = values.effStartDate[0]
            obj.effEndDate = values.effStartDate[1]
          }
          if (values.taskCode) obj.taskCode = values.taskCode
          if (values.timeNum) obj.timeNum = values.timeNum
          if (values.timeType) obj.timeType = values.timeType * 1
          if (values.week) obj.week = values.week.join(',')
          if (
            values.exStartDate &&
            values.exEndDate &&
            moment(values.exEndDate).hour() <= moment(values.exStartDate).hour()
          ) {
            message.error('任务执行点，截止小时数不能大于开始小时！')
            return
          }
          maintaskUpdateApi(obj).then(v => {
            message.success('更新成功')
            history.goBack()
          })
        },
        onCancel() {
          let obj = {}
          obj.id = id
          obj.effectiveTime = values.effectiveTime
          obj.executionType = values.executionType
          obj.executionMode =
            values.executionMode == null ? 3 : values.executionMode
          obj.monthType = values.monthType
          obj.monthDay = values.monthDay
          obj.projectId = values.projectId
          obj.startDate = values.startDate
          obj.taskCode = values.taskCode
          obj.updateType = values.updateType
          obj.aimsIds = values.aimsIds
          obj.sourceId = values.sourceId
          obj.isSubFile = values.isSubFile
          obj.timeList = values.timeList
          obj.isChangeDate = 1
          if (values.exStartDate) obj.exStartDate = values.exStartDate

          if (values.exEndDate) obj.exEndDate = values.exEndDate

          if (values.effectiveTime === 2) {
            obj.effStartDate = values.effStartDate[0]
            obj.effEndDate = values.effStartDate[1]
          }
          if (values.taskCode) obj.taskCode = values.taskCode
          if (values.timeNum) obj.timeNum = values.timeNum
          if (values.timeType) obj.timeType = values.timeType * 1
          if (values.week) obj.week = values.week.join(',')
          if (
            values.exStartDate &&
            values.exEndDate &&
            moment(values.exEndDate).hour() <= moment(values.exStartDate).hour()
          ) {
            message.error('任务执行点，截止小时数不能大于开始小时！')
            return
          }
          maintaskUpdateApi(obj).then(v => {
            message.success('更新成功')
            history.goBack()
          })
        }
      })
    })
  }
  render() {
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form
    getFieldDecorator('projectId', { initialValue: null })
    getFieldDecorator('taskCode', { initialValue: null })
    getFieldDecorator('updateType', { initialValue: null })
    getFieldDecorator('startDate', { initialValue: null })
    getFieldDecorator('sourceId', { initialValue: null })
    getFieldDecorator('isSubFile', { initialValue: null })
    getFieldDecorator('aimsIds', { initialValue: null })
    getFieldDecorator('effectiveTime', { initialValue: null })
    getFieldDecorator('effStartDate', { initialValue: null })
    getFieldDecorator('executionType', { initialValue: null })
    getFieldDecorator('executionMode', { initialValue: null })
    getFieldDecorator('week', { initialValue: null })
    getFieldDecorator('exStartDate', { initialValue: null })
    getFieldDecorator('exEndDate', { initialValue: null })
    getFieldDecorator('timeNum', { initialValue: null })
    getFieldDecorator('timeType', { initialValue: null })
    getFieldDecorator('monthType', { initialValue: null })
    getFieldDecorator('monthDay', { initialValue: null })
    getFieldDecorator('timeList', { initialValue: null })

    const { history } = this.props
    const { projectSource } = this.state
    const rules = {
      rules: [
        {
          required: true,
          message: '字符不得为空'
        }
      ]
    }
    const radioStyle = {
      display: 'block',
      height: '30px',
      lineHeight: '30px'
    }
    return (
      <div className="createTask">
        <Form layout="inline">
          <h3>任务信息</h3>
          <div className="createTask-row">
            <FormItem label="项目名称">
              {getFieldDecorator('projectId', rules)(
                <Select style={{ width: '176px' }} placeholder="请选择">
                  {projectSource.map(v => (
                    <Option key={v.id}>{v.projectName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <FormItem label="任务编号">
              {getFieldValue('taskCode')}
              {/* {getFieldDecorator('taskCode', rules)(<Input />)} */}
            </FormItem>
          </div>
          <div className="createTask-row">
            <FormItem label="文件更新方式">
              {getFieldDecorator('updateType', rules)(
                <RadioGroup>
                  <Radio style={radioStyle} value={1}>
                    增量（只更新上个执行时间点以后的文件）
                  </Radio>
                  <Radio style={radioStyle} value={2}>
                    差异（更新源地址有、而目标地址无的文件）
                  </Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem label="开始文件时间">
              {getFieldDecorator('startDate', rules)(
                <DatePicker
                  format="YYYY-MM-DD HH:mm:ss"
                  // showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                />
              )}
            </FormItem>
          </div>
          <h3>源产品信息</h3>
          <div className="createTask-row">
            <span style={{ color: '#000' }}>
              <FormItem label="源产品名称">
                {getFieldDecorator('sourceId', rules)(
                  <Select style={{ width: '400px' }}>
                    {this.state.productSource.map(product => {
                      return (
                        <Option key={product.id}>{product.productName}</Option>
                      )
                    })}
                  </Select>
                )}
              </FormItem>
              <FormItem label="是否包括子文件夹中源产品">
                {getFieldDecorator('isSubFile', rules)(
                  <RadioGroup>
                    <Radio value={1}>是</Radio>
                    <Radio value={2}>否</Radio>
                  </RadioGroup>
                )}
              </FormItem>
            </span>
          </div>
          <h3>目标信息</h3>
          <div className="createTask-row">
            <FormItem label="目标名称">
              {getFieldDecorator('aimsIds', rules)(
                <Select style={{ width: '400px' }} placeholder="请选择">
                  {this.state.userSource.map(user => {
                    return <Option key={user.id}>{user.userName}</Option>
                  })}
                </Select>
              )}
            </FormItem>
          </div>

          <h3>触发器</h3>
          <div className="createTask-row">
            <div>
              <FormItem label="任务有效时间段">
                {getFieldDecorator('effectiveTime', rules)(
                  <RadioGroup
                    onChange={e => {
                      if (e.target.value === 2) {
                        this.setState({
                          effStartDate: true
                        })
                      } else {
                        this.setState({
                          effStartDate: false
                        })
                      }
                    }}
                  >
                    <Radio value={1}>永久</Radio>
                    <Radio value={2}>自定义</Radio>
                  </RadioGroup>
                )}
              </FormItem>
              {this.state.effStartDate && (
                <FormItem>
                  {getFieldDecorator('effStartDate', rules)(
                    <DatePicker.RangePicker />
                  )}
                </FormItem>
              )}
            </div>
            <div>
              <FormItem label="任务执行时点">
                {getFieldDecorator('executionType', rules)(
                  <RadioGroup
                    onChange={e => {
                      this.setState({
                        executionType: e.target.value,
                        executionMode: null
                      })
                      setFieldsValue({ executionMode: null })
                    }}
                  >
                    <Radio value={1}>每天</Radio>
                    <Radio value={2}>每周</Radio>
                    <Radio value={4}>每月</Radio>
                    <Radio value={3}>实时</Radio>
                  </RadioGroup>
                )}
              </FormItem>
              {this.state.executionType === 2 && (
                <div>
                  <FormItem label="指定">
                    {getFieldDecorator('week', rules)(
                      <Checkbox.Group style={{ width: '100%' }}>
                        <Checkbox value="1">周一</Checkbox>
                        <Checkbox value="2">周二</Checkbox>
                        <Checkbox value="3">周三</Checkbox>
                        <Checkbox value="4">周四</Checkbox>
                        <Checkbox value="5">周五</Checkbox>
                        <Checkbox value="6">周六</Checkbox>
                        <Checkbox value="7">周日</Checkbox>
                      </Checkbox.Group>
                    )}
                  </FormItem>
                </div>
              )}
              {(this.state.executionType === 1 ||
                this.state.executionType === 2) && (
                <div>
                  <FormItem label="执行方式">
                    {getFieldDecorator('executionMode', rules)(
                      <RadioGroup
                        onChange={e =>
                          this.setState({
                            executionMode: e.target.value
                          })
                        }
                      >
                        <Radio value={0}>执行一次</Radio>
                        <Radio value={1}>执行多次(有规律)</Radio>
                        <Radio value={2}>执行多次(无规律)</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                </div>
              )}
              {(this.state.executionType === 1 ||
                this.state.executionType === 2) &&
                this.state.executionMode === 0 && (
                  <div>
                    <FormItem label="开始时间">
                      {getFieldDecorator('exStartDate', rules)(
                        <TimePicker format="HH:mm" />
                      )}
                    </FormItem>
                  </div>
                )}
              {(this.state.executionType === 1 ||
                this.state.executionType === 2) &&
                this.state.executionMode === 1 && (
                  <div>
                    <FormItem label="起止时间">
                      {getFieldDecorator('exStartDate', rules)(
                        <TimePicker format="HH" />
                      )}
                    </FormItem>
                    <FormItem>
                      {getFieldDecorator('exEndDate', rules)(
                        <TimePicker format="HH" />
                      )}
                    </FormItem>
                    <FormItem label="每隔">
                      {getFieldDecorator('timeNum', rules)(<InputNumber />)}
                    </FormItem>
                    <FormItem>
                      {getFieldDecorator('timeType', rules)(
                        <Select style={{ width: '80px' }}>
                          <Option key={'1'}>分</Option>
                          <Option key={'2'}>小时</Option>
                        </Select>
                      )}
                    </FormItem>
                  </div>
                )}
              {(this.state.executionType === 1 ||
                this.state.executionType === 2) &&
                this.state.executionMode === 2 && (
                  <div>
                    <FormItem label="时间">
                      {getFieldDecorator('timeList', rules)(
                        <Input
                          placeholder="格式：19:05;14:20"
                          style={{ width: '300px' }}
                        />
                      )}
                    </FormItem>
                  </div>
                )}
              {this.state.executionType === 4 && (
                <div>
                  <FormItem label="指定">
                    {getFieldDecorator('monthType', rules)(
                      <RadioGroup
                        onChange={e =>
                          this.setState({
                            monthType: e.target.value
                          })
                        }
                      >
                        <Radio value={0}>最后一天</Radio>
                        <Radio value={1}>自定义</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                  {this.state.monthType === 1 && (
                    <FormItem label="每月">
                      {getFieldDecorator('monthDay', rules)(
                        <Select style={{ width: '80px' }}>
                          {Array.from(Array(31), (_, k) => k + 1).map(i => (
                            <Option key={i.toString()}>{i}</Option>
                          ))}
                        </Select>
                      )}
                      日
                    </FormItem>
                  )}
                </div>
              )}
            </div>
          </div>
        </Form>
        <div style={{ textAlign: 'center' }}>
          <Button onClick={() => history.goBack()}>取消</Button>
          &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
          <Button type="primary" onClick={this.save}>
            保存
          </Button>
        </div>
      </div>
    )
  }
}

export default Form.create()(EditTask)
